<template>
  <div class="app-container">
    <!-- 搜索和操作按钮区域 - 单行布局 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.kw"
        placeholder="输入关键词"
        size="mini"
        class="filter-item search-input"
        @keyup.enter.native="handleFilter"
      />
      <el-button v-waves size="mini" class="filter-item search-btn" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button size="mini" class="filter-item add-btn" icon="el-icon-plus" @click="handleCreate">
        添加
      </el-button>
    </div>

    <!-- 表格区域 - 简化列宽和内容显示 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      size="mini"
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="关键词" min-width="120px">
        <template slot-scope="scope">
          <span class="clickable-text" @click="copyToClipboard(scope.row.keyword)">{{ scope.row.keyword }}</span>
        </template>
      </el-table-column>
      <el-table-column label="链接" min-width="150px">
        <template slot-scope="scope">
          <span class="clickable-text" @click="copyToClipboard(scope.row.link)">{{ scope.row.link }}</span>
        </template>
      </el-table-column>
      <el-table-column label="NoFollow" width="70px" align="center">
        <template slot-scope="scope">
          <el-tag size="mini" :type="scope.row.is_nofollow ? 'success' : 'info'">
            {{ scope.row.is_nofollow ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="100">
        <template slot-scope="{row}">
          <el-button type="text" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" type="text" size="mini" class="delete-btn" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 - 简化布局 -->
    <el-pagination
      v-if="total > 0"
      background
      :current-page="listQuery.page"
      :page-sizes="[10,20]"
      :page-size="listQuery.limit"
      layout="prev, pager, next"
      :total="total"
      class="pagination-container"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <!-- 表单弹窗 - 调整宽度和布局 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="top"
        size="mini"
        style="margin: 0 auto;"
      >
        <el-form-item label="目标网站" prop="keyword">
          <el-input v-model="temp.root_domain" placeholder="请直接输入域名，不需要带http,https" />
        </el-form-item>
        <el-form-item label="关键词" prop="keyword">
          <el-input v-model="temp.keyword" placeholder="请输入内容多个关键词换行或者逗号分割" class="input-with-select" type="textarea" :rows="5" />
          <el-button icon="el-icon-search" :loading="aiLoading" @click="handleGetKeywordList(temp.keyword)">AI扩展关键词</el-button>
        </el-form-item>
        <el-form-item label="链接" prop="link">
          <el-input v-model="temp.link" />
        </el-form-item>

        <el-form-item label="是否NoFollow">
          <el-switch v-model="temp.is_nofollow" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button size="mini" type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/cms/cmsm'
import { Post as GetAiContent } from '@/api/cms/openai'
import waves from '@/directive/waves'
import qs from 'qs'

export default {
  name: 'CmsInnerLink',
  directives: { waves },
  props: {
    domain: {
      type: String,
      required: false
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        kw: undefined,
        table_name: 'InnerLink'
      },
      temp: {
        id: undefined,
        root_domain: this.domain,
        keyword: '',
        link: '',
        is_nofollow: false
      },
      dialogFormVisible: false,
      dialogStatus: '',
      aiLoading: false,
      textMap: {
        update: '编辑内链',
        create: '创建内链'
      },
      rules: {
        keyword: [{ required: true, message: '关键词是必填的', trigger: 'blur' }],
        link: [{ required: true, message: '链接是必填的', trigger: 'blur' }]
      }
    }
  },
  watch: {
    domain: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          console.log('root domain:', newVal)
          this.listQuery.kw = newVal
          this.temp.root_domain = newVal
          this.getList()
        }
      },
      immediate: true
    }
  },
  created() {
    this.getList()
  },
  methods: {
    copyToClipboard(text) {
      navigator.clipboard.writeText(text).then(() => {
        this.$message({
          message: '已复制到剪贴板',
          type: 'success',
          duration: 1500
        })
      }).catch(err => {
        this.$message({
          message: '复制失败',
          type: 'error',
          duration: 1500
        })
        console.error('无法复制: ', err)
      })
    },
    handleGetKeywordList(keyowrd) {
      const prompt = 'Please help expand the list of keywords related to B2B business, and provide only the expanded keyword list as the result without any explanation.\n' +
        '# Requirements\n' +
        '1. Please fully consider that I am a b2b business\n' +
        '2. The keywords are strongly related, preferably including the core words in my core words\n' +
        '3. Give up to 10\n' +
        '4 One keyword per line\n' +
        '5 no extra characters, no bullet points, no extra numbering\n' +
        '# Output format\n' +
        '\n' +
        '- The expanded keyword list, only separate multiple keywords with commas.\n' +
        '\n' +
        '# Example\n' +
        '\n' +
        'Input keyword: "sports wear"\n' +
        '\n' +
        'Output: "ports wear wholesale\nports wear manufacture\nports wear suppplier\nsports wear bulk"\n' +
        'My keywords are:' + keyowrd
      this.aiLoading = true
      GetAiContent({ prompt: prompt, engine: 'gpt-4o', aiprompt_id: '', keywords: [] })
        .then(response => {
          // console.log(response.content)
          this.temp.keyword = this.temp.keyword + '\n' + response.original_content
          // 如果有双引号，去掉
          this.temp.keyword = this.temp.keyword.replace(/\"/g, '')
          this.aiLoading = false
        }).catch(e => {
          console.log('error')
          this.addCustomerVisible = true
          this.aiLoading = false
        })
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        ...this.listQuery,
        root_domain: this.domain,
        pagesize: this.listQuery.limit,
        page: this.listQuery.page
      })).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      }).catch(err => {
        console.log(err)
        this.listLoading = false
      })
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handlePageChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        root_domain: this.domain,
        keyword: '',
        link: '',
        is_nofollow: false
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        if (this.$refs.dataForm) {
          this.$refs.dataForm.clearValidate()
        }
      })
    },
    createData() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.temp.table_name = 'InnerLink'
          if ('create_at' in this.temp) delete (this.temp.create_at, { table_name: 'InnerLink', domain: this.domain })
          // 按换行符号分割关键词，单独批量添加
          const keywords = this.temp.keyword.split(/[\n,]/).filter(item => item.trim() !== '')
          for (let i = 0; i < keywords.length; i++) {
            this.temp.keyword = keywords[i]
            Post(this.temp).then(() => {
              this.dialogFormVisible = false
              this.getList()
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        if (this.$refs.dataForm) {
          this.$refs.dataForm.clearValidate()
        }
      })
    },
    updateData() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.table_name = 'InnerLink'
          if ('create_at' in this.temp) delete (this.temp.create_at)
          Put(tempData.id, tempData).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if ('create_at' in this.temp) delete (this.temp.create_at)
        Delete(row.id, { table_name: 'InnerLink', domain: this.domain }).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 10px;
  width: 100%;
}

.filter-container {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.search-input {
  flex: 1;
}

.filter-item {
  margin: 0;
}

.search-btn {
  background-color: #1EB7E6;
  border-color: #1EB7E6;
  color: white;

  &:hover, &:focus {
    background-color: #17a2ce;
    border-color: #17a2ce;
    color: white;
  }
}

.add-btn {
  background-color: #67C23A;
  border-color: #67C23A;
  color: white;

  &:hover, &:focus {
    background-color: #5daf34;
    border-color: #5daf34;
    color: white;
  }
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}

.delete-btn {
  color: #F56C6C;
  margin-left: 8px;
}

.clickable-text {
  cursor: pointer;
  color: #409EFF;
  transition: color 0.3s;
}

.clickable-text:hover {
  color: #66b1ff;
  text-decoration: underline;
}

/* 调整表格内容的显示 */
:deep(.el-table) {
  font-size: 12px;
}

:deep(.el-table td) {
  padding: 4px 0;
}

:deep(.el-dialog__body) {
  padding: 15px;
}

:deep(.el-form-item) {
  margin-bottom: 15px;
}

:deep(.el-form-item__label) {
  padding-bottom: 4px;
}
</style>
